﻿using System.Web.Mvc;
using AutoMapper;
using SolidDemo.Business.Interfaces;
using SolidDemo.Data.Enums;
using SolidDemo.Data.ProjectData;
using SolidDemo.Models.Select;

namespace SolidDemo.Controllers
{
    public class SelectController : GomtuuController
    {
        private readonly IProjectFactory _projectFactory;
        private readonly IPumpSelectService _selectService;

        public SelectController(IProjectFactory projectFactory, IPumpSelectService selectService, IGenericRepository repository, ILogRepository logRepository)
            : base(repository, logRepository)
        {
            _projectFactory = projectFactory;
            _selectService = selectService;
        }

        [HttpGet]
        public ActionResult Pump(bool gen = false, bool isStocked = false, int diameter = 0, double minFlow = 0, double maxFlow = 0)
        {
            var model = new PumpModel();

            model.IsStocked = isStocked;
            model.DiameterMm = diameter;
            model.MinFlowLperMin = minFlow;
            model.MaxFlowLPerMin = maxFlow;

            if (!gen) return View(model);

            model.IsShowResults = true;
            model.Pumps = _selectService.SelectBy_Stocked_DiameterMm_MinFlowLpm_MaxFlowLpm(model.IsStocked, model.DiameterMm, model.MinFlowLperMin, model.MaxFlowLPerMin);

            return View(model);
        }

        [HttpPost]
        public ActionResult Pump(PumpModel model)
        {
            return RedirectToAction("Pump", new { gen = true, isStocked = model.IsStocked, diameter = model.DiameterMm, minFlow = model.MinFlowLperMin, maxFlow = model.MaxFlowLPerMin });
        }

        [HttpGet]
        public ActionResult Pump2(int id = 0, bool gen = false)
        {
            var model = new PumpModel();
            var project = _projectFactory.Load(id);

            if (project == null) return View(model);

            Mapper.CreateMap<PumpSelectProject, PumpModel>().ForMember(dest => dest.ProjectId, opts => opts.MapFrom(src => src.Id));
            Mapper.Map(project, model);

            //model.ProjectId = project.Id;

            if (!gen) return View(model);

            model.IsShowResults = true;
            model.Pumps = _selectService.SelectBy_Stocked_DiameterMm_MinFlowLpm_MaxFlowLpm(model.IsStocked, model.DiameterMm, model.MinFlowLperMin, model.MaxFlowLPerMin);

            return View(model);
        }

        [HttpPost]
        public ActionResult Pump2(PumpModel model)
        {
            var project = _projectFactory.LoadOrCreate(model.ProjectId, EProjectType.SelectPump);

            Mapper.CreateMap<PumpModel, PumpSelectProject>();
            Mapper.Map(model, project);
            _repository.Save(project);

            return RedirectToAction("Pump2", new { id = project.Id, gen = true });
        }
    }
}